package com.dongdongshop.consumMq;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dongdongshop.mapper.TbSeckillOrderMapper;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbSeckillOrder;
import com.dongdongshop.utils.IdWorker;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@RocketMQMessageListener(topic = "create-order-seckill",consumerGroup = "seckill-group-consum")
public class CreateOrderConsum implements RocketMQListener<String> {
    
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TbSeckillOrderMapper seckillOrderMapper;
    

    @Override
    public void onMessage(String message) {
        JSONObject jsonObject = JSONUtil.parseObj(message);
        Long goodsId = Long.parseLong(jsonObject.get("goodsId").toString());
        String userName = (String) jsonObject.get("userName");

        TbSeckillGoods goods = (TbSeckillGoods) redisTemplate.boundHashOps("seckills").get(goodsId);
//        下单
        TbSeckillOrder order = new TbSeckillOrder();
        IdWorker idWorker = new IdWorker();
        long orderId = idWorker.nextId();
        order.setId(orderId);//订单id
        order.setUserId(userName);//买家id
        order.setSellerId(goods.getSellerId());
        order.setSeckillId(goodsId);//商品id
        order.setMoney(goods.getCostPrice());//付款jine = 秒杀价
        order.setCreateTime(new Date());//创建时间
        order.setStatus("0");//待支付
        seckillOrderMapper.insertSelective(order);

//        订单生成之后要放入缓存 key userId value oredId
        redisTemplate.boundValueOps("order"+userName).set(orderId);
    }
}
